// pages/order/createOrder/createOrderNext.js

const app = getApp();
let api = require('../../../utils/api.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    freight: 0,
    showgoodsNameId: 0,
    showloadListId: 0,
    isShow_06: false,
    listData_06: [],
    isShow_07: false,
    listData_07: [],
    picker_07_data: [],
    picker_06_data: [],
    value: '',
    goodsNameList: [],
    loadList: [],
    requirement: []
  },
  mGetDate: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var d = new Date(year, month, 0);
    return d.getDate();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.data);
    var that = this;
    that.getSetting();

    var lastMonth = [];
    // var today = new Date();
    var time = new Date().getHours();
    // console.log(time);
    lastMonth[0] = {
      name: '今天',
      children: [],
      id: 0
    };
    lastMonth[1] = {
      name: '明天',
      children: [],
      id: 1
    }
    var date = new Date();

    var monthDate = that.mGetDate() - date.getDate()
    console.log(monthDate)


    for (var i = 2; i < monthDate; i++) {
      var date1 = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + i)
      var name = date1.replace(/-/g, "/")

      var md = {
        name: name,
        children: [],
        id: i
      };
      lastMonth.push(md);
    }

    for (var j = 1; j < date.getDate(); j++) {
      var date1 = date.getFullYear() + '-' + (date.getMonth() + 2) + '-' + (j)
      var name = date1.replace(/-/g, "/")
      var md = {
        name: name,
        children: [],
        id: i
      };
      lastMonth.push(md);
    }
    lastMonth.forEach(function (value, index, arrSelf) {
      var morning = {
        name: "上午",
        children: [{
          name: "都可以",
          id: index + 1,
        }],
        id: index
      };
      for (var j = 0; j < 13; j++) {
        var md = {
          name: j + ':00',
          id: index + j + 1
        }
        morning.children.push(md);
      }
      var afternoon = {
        name: "下午",
        children: [{
          name: "都可以",
          id: index + 1,
        }],
        id: index
      };
      for (var j = 13; j < 19; j++) {
        var md = {
          name: j + ':00',
          id: index + j + 1
        }
        afternoon.children.push(md);
      }
      var night = {
        name: "晚上",
        children: [{
          name: "都可以",
          id: index + 1,
        }],
        id: index
      }
      for (var j = 19; j < 24; j++) {
        var md = {
          name: j + ':00',
          id: index + j
        }
        night.children.push(md);
      }
      if (index == 0) {
        if (time >= 0 && time <= 12) {
          var morning = {
            name: "上午",
            children: [{
              name: "都可以",
              id: index + 1,
            }],
            id: index
          };
          for (var j = time; j < 13; j++) {
            var md = {
              name: j + ':00',
              id: index + j
            }
            morning.children.push(md);
          }

          value.children.push(morning);
          value.children.push(afternoon);
          value.children.push(night);
        }
        if (time > 12 && time <= 18) {
          var afternoon = {
            name: "下午",
            children: [{
              name: "都可以",
              id: index + 1,
            }],
            id: index
          };
          for (var j = time; j < 19; j++) {
            var md = {
              name: j + ':00',
              id: index + j
            }
            afternoon.children.push(md);
          }
          value.children.push(afternoon);
          value.children.push(night);
        }
        if (time > 18 && time <= 24) {
          var afternoon = {
            name: "晚上",
            children: [{
              name: "都可以",
              id: index + 1,
            }],
            id: index
          };
          for (var j = time; j < 19; j++) {
            var md = {
              name: j + ':00',
              id: index + j
            }
            night.children.push(md);
          }
          value.children.push(night);
        }
      } else {

        value.children.push(morning);
        value.children.push(afternoon);
        value.children.push(night);
      }


    });

    that.setData({
      'listData_06': lastMonth,
      'listData_07': lastMonth,
      lastData: JSON.parse(options.data) // 字符串转对象
    })
    wx.getSystemInfo({
      success: function (res) {
        that.getMoney()
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight - app.globalData.navHeight
        });
      }
    });
  },
  // 创建订单
  createOrder: function (e) {
    var that = this;
    var data = that.data;
    if (data.picker_06_data.length == 0 || data.picker_07_data.length == 0 || !data.goodName || !data.remarkShow || !data.freight) {
      wx.showToast({
        title: '请输入完整信息',
        icon: 'none',
      });
      return;
    }
    // 调起客户端小程序订阅消息界面，返回用户订阅消息的操作结果
    wx.requestSubscribeMessage({
      tmplIds: ['OWpfTyHgQhmAUWM9JzNNetZ9ARRMuLOBotwajyxzMTk', 'bbB6bhCa9IFS0dl3nYBlIuzEVDfiKMrdhxyghRPcWoI', 'tpNacyhXiqfARxXzt8AR-cTWTpKYknvQ0McvuRs98nU'], // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
      success(res) {
        // console.log('已授权接收订阅消息')
      }
    })
    var shipmentTime = that.changeTime(data.picker_06_data);
    var arrivalTime = that.changeTime(data.picker_07_data);

    var specialAsk = []
    this.data.requirement.forEach(function (value, index) {
      if (value.isSelected == true) {
        specialAsk.push(value.content);
      }
    });
    var lastData = this.data.lastData;
    var param = {
      // 到货时间
      "arrivalTime": {
        "end": arrivalTime['end'],
        "start": arrivalTime['start']
      },
      // 运费
      "freight": this.data.freight,
      // 货物体现
      "freightBulk": {
        "max": lastData.freightBulk['max'],
        "min": lastData.freightBulk['min']
      },
      // 货物名称
      "freightName": this.data.goodName,
      // 货物重量
      "freightWeight": {
        "max": lastData.freightWeight['max'],
        "min": lastData.freightWeight['min']
      },
      // 出发地
      "from": {
        "province": lastData.fromProvince,
        "city": lastData.fromProvince + '|' + lastData.fromCity,
        "address": lastData.fromAddress
      },
      // 几装几卸
      "hand": this.data.loadList[this.data.showloadListId]['content'],
      "isAgreement": 1,
      "isInsurance": 0,
      "remarks": this.data.remarks,
      "shipmentTime": {
        "end": shipmentTime['end'],
        "start": shipmentTime['start']
      },
      "specialAsk": specialAsk,
      // 目的地
      "to": {
        "address": lastData.toAddress,
        "city": lastData.toProvince + '|' + lastData.toCity,
        "province": lastData.toProvince
      },
      "useVehicleType": lastData.useVehicleType,
      "vehicleLen": lastData.vehicleLen,
      "vehicleModel": lastData.vehicleModel
    }

    var token = wx.getStorageSync('TOKEN')
    api._post('/omc/order/create', param, token).then(res => {
      // console.log(res);
      if (res.code == 200) {
        wx.switchTab({
          url: '/pages/index/index',
          success: function (e) {
            var page = getCurrentPages().pop();
            if (page == undefined || page == null) return;
            page.onLoad();
          }
        })
      } else if (res.code > 400) {
        wx.navigateTo({
          url: '../login/login',
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }
    }).catch(e => {
      // console.log(e)
    })
  },


  showPicker_06: function () {
    this.setData({
      isShow_06: true
    })
  },

  sureCallBack_06(e) {
    let data = e.detail
    this.setData({
      isShow_06: false,
      picker_06_data: e.detail.choosedData,
      picker_06_index: e.detail.choosedIndexArr

    })
  },
  cancleCallBack_06() {
    this.setData({
      isShow_06: false,
    })
  },

  showPicker_07: function () {
    this.setData({
      isShow_07: true
    })
  },

  sureCallBack_07(e) {
    // console.log(e.detail)
    let data = e.detail
    this.setData({
      isShow_07: false,
      picker_07_data: e.detail.choosedData,
      picker_07_index: e.detail.choosedIndexArr

    })
  },
  cancleCallBack_07() {
    this.setData({
      isShow_07: false,
    })
  },
  /*
   * 选择货物名称
   */
  setGoodsName: function (e) {

    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showCarModelStatus: true,
      showModelStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      });
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      keyboardHeight: 0
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showCarModelStatus: false,
        showModelStatus: false,
        showRemarkModelStatus: false,
        keyboardHeight: 0
      })
    }.bind(this), 200)
  },
  // 获取键盘高度
  keyBoardHeight: function (e) {
    this.setData({
      keyboardHeight: e.detail.height
    });
  },
  setRemark: function (e) {

    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showRemarkModelStatus: true,
      showModelStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      });
    }.bind(this), 200)
  },
  // 自定义货物名称
  setCustomGoodName: function (e) {

    this.setData({
      setCustomGood: true,
      showgoodsNameId: 'custom'
    })

  },
  choose: function (e) {
    var that = this;
    var data = that.data;
    var key = e.currentTarget.dataset.key;
    var type = e.currentTarget.dataset.type;
    // console.log
    that.setData({
      setCustomGood: false,
      [type]: e.currentTarget.dataset.key,
    })
  },
  // 获取自定义货物名称
  customGoodInput: function (e) {
    this.setData({
      customGood: e.detail.value
    })
    // console.log(this.data.customGood)
  },
  // 确认货物名称
  confirmGoodName: function (e) {
    var that = this;
    var data = that.data;
    if (data.showgoodsNameId == 'custom') {
      if (data.customGood) {
        var freightName = data.customGood;
      } else {
        wx.showToast({
          title: '请输入货物名称',
          icon: 'none',
        })
        return;
      }
    } else {
      var freightName = data.goodsNameList[data.showgoodsNameId].content;
    }
    // console.log(freightName);
    this.setData({
      goodName: freightName,
    })

    this.hideModal();
  },
  requirementSelected: function (e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.requirement[index];
    item.isSelected = !item.isSelected;
    this.setData({
      requirement: this.data.requirement,
    });
  },
  remarks: function (e) {
    this.setData({
      remarks: e.detail.value
    })
    // console.log(this.data.remarks)
  },
  // 确认服务要求和备注
  confirmRemark: function (e) {
    // console.log(e);
    this.setData({
      remarkShow: this.data.loadList[this.data.showloadListId]['content']
    });
    this.hideModal();
  },
  // 运费设置
  setFreight: function (e) {
    var that = this;
    // console.log(e);
    var money = '';
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) { //正则验证，提现金额小数点后不能大于两位数字
      money = e.detail.value;
      // console.log(money);
    } else {
      money = e.detail.value.substring(0, e.detail.value.length - 1);
      e.detail.value = e.detail.value.substring(0, e.detail.value.length - 1);
    }

    that.setData({
      freight: money
    })
    // console.log(this.data.freight)
  },
  /**
   * 时间修改时间戳
   */
  changeTime: function (data) {
    // console.log(data);
    var shipmentTime = [];
    var startTime = data[0]['name'] + ' ' + data[2]['name']
    if (data[0]['name'] == '今天') {
      data[0]['name'] = new Date(new Date().setDate(new Date().getDate())).toLocaleDateString();
      startTime = data[0]['name'] + ' ' + data[2]['name'];
      if (data[2]['name'] == '都可以') {
        if (data[1]['name'] == '上午') {
          shipmentTime['start'] = Date.parse(new Date()) / 1000;
          shipmentTime['end'] = Date.parse(new Date(data[0]['name'] + ' 12:00')) / 1000;
        }

        if (data[1]['name'] == '下午') {
          shipmentTime['start'] = Date.parse(new Date()) / 1000;
          shipmentTime['end'] = Date.parse(new Date(data[0]['name'] + ' 18:00')) / 1000;
        }

        if (data[1]['name'] == '晚上') {
          shipmentTime['start'] = Date.parse(new Date()) / 1000;
          shipmentTime['end'] = Date.parse(new Date(data[0]['name'] + ' 24:00')) / 1000;
        }

      } else {
        shipmentTime['start'] = Date.parse(new Date(startTime)) / 1000;
        shipmentTime['end'] = Date.parse(new Date(startTime)) / 1000;
      }

    } else {
      if (data[0]['name'] == '明天') {
        data[0]['name'] = new Date(new Date().setDate(new Date().getDate() + 1)).toLocaleDateString();
        startTime = data[0]['name'] + ' ' + data[2]['name'];
      } else {
        startTime = data[0]['name'] + ' ' + data[2]['name'];
      }
      if (data[2]['name'] == '都可以') {
        if (data[1]['name'] == '上午') {
          shipmentTime['start'] = Date.parse(new Date(data[0]['name'] + ' 00:00')) / 1000;
          shipmentTime['end'] = Date.parse(new Date(data[0]['name'] + ' 12:00')) / 1000;
        }
        if (data[1]['name'] == '下午') {
          shipmentTime['start'] = Date.parse(new Date(data[0]['name'] + ' 13:00')) / 1000;
          shipmentTime['end'] = Date.parse(new Date(data[0]['name'] + ' 18:00')) / 1000;
        }
        if (data[1]['name'] == '晚上') {
          shipmentTime['start'] = Date.parse(new Date(data[0]['name'] + ' 19:00')) / 1000;
          shipmentTime['end'] = Date.parse(new Date(data[0]['name'] + ' 24:00')) / 1000;
        }
      } else {
        shipmentTime['start'] = Date.parse(new Date(startTime)) / 1000;
        shipmentTime['end'] = Date.parse(new Date(startTime)) / 1000;
      }
    }
    // console.log(startTime)
    return shipmentTime;
  },
  getSetting: function () {
    var that = this;
    var token = wx.getStorageSync('TOKEN')
    api._get('/setting/get/info/1', '', token).then(res => {
      // console.log(res);
      if (res.code == 200) {
        that.setData({
          goodsNameList: res.result
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }
    }).catch(e => {
      // console.log(e)
    })
    api._get('/setting/get/info/2', '', token).then(res => {
      // console.log(res);
      if (res.code == 200) {
        that.setData({
          loadList: res.result
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }
    }).catch(e => {
      // console.log(e)
    })
    api._get('/setting/get/info/3', '', token).then(res => {
      // console.log(res);
      if (res.code == 200) {
        that.setData({
          requirement: res.result
        })
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }
    }).catch(e => {
      // console.log(e)
    })
  },
  setMoney: function () {
    var that = this;
    // console.log(that.data.lastData)
    that.setData({
      freight: that.data.systemMoney
    })
  },

  getMoney: function () {

    return new Promise(resolve => {
      var that = this;
      var params = {
        from: that.data.lastData.fromProvince + that.data.lastData.fromCity + that.data.lastData.fromAddress,
        to: that.data.lastData.toProvince + that.data.lastData.toCity + that.data.lastData.toAddress
      }

      var token = wx.getStorageSync('TOKEN')
      api._post('/setting/get/advice/price', params, token).then(res => {
        // console.log(res);
        that.setData({
          systemMoney: res.result
        })
        // console.log(that.data)
      })
      return resolve()
    })

  },
})